package com.jhj.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

/**
 * json处理
 *
 */
public class JsonUtil {
	/**
	 * map转json
	 *
	 * @param map
	 * @return
	 */
	public static JsonObject mapTojson(Map map) {
		JsonObject j = new JsonObject();
		j.addProperty(new Gson().toJson(map), true);
		return j;
	}

	/**
	 * string转json
	 *
	 * @param str
	 * @return
	 */
	public static JsonObject stringTojson(String str) {
		JsonObject j = new JsonObject();
		j.addProperty(str, true);
		return j;
	}

	/**
	 * json转map
	 *
	 * @param str
	 * @return
	 */
	public static Map<String, Object> stringToMap(String str) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		Map<String, Object> map = g.fromJson(str,
				new TypeToken<Map<String, Object>>() {
				}.getType());
		return map;
	}

	/**
	 * list转json
	 *
	 * @param list
	 * @return
	 */
	public static <T> String listTojson(List<T> list) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		return g.toJson(list);
	}

	public static String objectTojson(Object o) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		return g.toJson(o);
	}

	/**
	 * json转List<T>
	 *
	 * @param str
	 * @return
	 */
	public static <T> List<T> convert(String str) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		List<T> map = g.fromJson(str, new TypeToken<List<T>>() {
		}.getType());
		return map;
	}
	
	public static void main(String[] args) {
//		String jsonStr = "[{\"time\":\"2017-07-07 12:01\", \"ad\"},{}]"
		Map<String, String> item1 = new HashMap<String, String>();
		item1.put("time", "2017-07-07 12:01");
		item1.put("adminName", "lianningchang");
		item1.put("action", "提交申请");
		item1.put("remarks", "订单收入由19.00 改为 20.00");
		
		Map<String, String> item2 = new HashMap<String, String>();
		item2.put("time", "2017-07-07 12:11");
		item2.put("adminName", "谷雨");
		item2.put("action", "审批通过");
		item2.put("remarks", "aaaa");
		
		List<Map<String,String>> logMaps = new ArrayList<Map<String, String>>();
		logMaps.add(item1);
		logMaps.add(item2);
		
		String jsonStr = JsonUtil.listTojson(logMaps);
		
		System.out.println(jsonStr);
		
		
		List<Map<String, String>> ll = JsonUtil.convert(jsonStr);
		System.out.println(ll.toString());
		
		Map<String, String> item3 = new HashMap<String, String>();
		item3.put("time", "2017-07-07 12:11");
		item3.put("adminName", "lianningchang");
		item3.put("action", "申请");
		item3.put("remarks", "订单收入由19.00 改为 21.00");
		ll.add(item3);
		jsonStr = JsonUtil.listTojson(ll);
		
		System.out.println(jsonStr);
	}
	
}
